package com.stiff.web.controller;

import com.stiff.web.bean.Item;
import com.stiff.web.bean.Order;
import com.stiff.web.service.ItemService;
import com.stiff.web.service.OrderService;
import com.stiff.web.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

@RequestMapping("order")
@Controller
public class OrderController {
    @Autowired
    private ItemService itemService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private UserService userService;
    /**
     * 跳转到订单页面
     * @param itemId
     * @return
     */
    @RequestMapping(value = "{itemId}",method = RequestMethod.GET)
    public ModelAndView toOrder(@PathVariable("itemId")Long itemId){
        ModelAndView mv = new ModelAndView("order");
        Item item = this.itemService.queryItemById(itemId);
        mv.addObject("item",item);
        return mv;
    }

    /**
     * 提交订单
     * @param order
     * @return
     */
    @RequestMapping(value = "submit",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> submitOrder(Order order){
        Map<String,Object> result = new HashMap<>();
        String orderId = this.orderService.submitOrder(order);
        if(StringUtils.isEmpty(orderId)){
            //提交失败
            result.put("status",300);
        }else {
            //提交成功
            result.put("status",200);
            result.put("data",orderId);
        }
        return result;
    }
    @RequestMapping(value = "success",method = RequestMethod.GET)
    public ModelAndView success(@RequestParam("id")Long orderId){
        ModelAndView mv = new ModelAndView("success");
        Order order = this.orderService.queryOrderById(orderId);
        mv.addObject("order",order);
        mv.addObject("date",new DateTime().plusDays(2).toString("MM月dd日"));
        return mv;
    }
}